import React, { useCallback, useState } from 'react';
import zhCN from 'antd/es/locale/zh_CN';
import { ConfigProvider } from 'antd';
import SettingContext from './index';
import setting from './setting';
import localStorage from '../utils/localStorage';

// const updateColorWeak = colorWeak => {
//   const root = document.getElementById('root');
//
//   if (root) {
//     root.className = colorWeak ? 'colorWeak' : '';
//   }
// };
const localName = 'setting';

// 用于setting数据流的处理
function SettingProvider(props) {
  const { children } = props;
  const [value, setValue] = useState(() => {
    const localSetting = localStorage.getItem(localName, false, true) || {};
    if (
      localSetting.primaryColor &&
      localSetting.primaryColor !== setting.primaryColor
    ) {
      window?.less
        ?.modifyVars({ '@primary-color': localSetting.primaryColor })
        .then(() => {})
        .catch((error) => {
          // eslint-disable-next-line
          console.log(error);
        });
    }
    return {
      ...setting,
      ...localSetting,
    };
  });

  // 更新setting数据
  const updateLayoutSetting = useCallback(
    (obj) => {
      const newState = { ...value, ...obj };
      // todo 后续如果有修改宽度可以加上这都代码
      // if (contentWidth && state.contentWidth !== contentWidth && window.dispatchEvent) {
      //   window.dispatchEvent(new Event('resize'));
      // }
      localStorage.setItem(localName, newState);
      setValue(newState);
    },
    [value],
  );

  return (
    <SettingContext.Provider
      value={{ ...value, updateLayoutSettingState: updateLayoutSetting }}
    >
      <ConfigProvider locale={zhCN}>{children}</ConfigProvider>
    </SettingContext.Provider>
  );
}

export default SettingProvider;
